package com.simple_frame.utils;

import cn.idev.excel.FastExcel;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.concurrent.ExecutorService;

public class ExcelUtil {
    @Resource
    private ExecutorService executorService;
    
    public final String EXCEL_FORMAT_PATTERN_ERROR = "文件格式错误，请上传xls或xlsx格式的文件";
    
    public boolean verifyExcel(String fileName) {
        return FileUtil.verifyFile(fileName, FileUtil.EXCEL_FORMAT_PATTERN);
    }
    
    public void writeToLocal(
            String fileName,
            Class<?> clazz,
            String sheetName,
            Collection<?> collection
    ) {
        FastExcel.write(fileName + ".xlsx", clazz).sheet(sheetName).doWrite(collection);
    }
    
    public <T> Collection<T> readFromLocal(
            String fileName,
            Class<T> clazz
    ) {
        if (!FileUtil.verifyFile(fileName, FileUtil.EXCEL_FORMAT_PATTERN)) {
            throw new RuntimeException(EXCEL_FORMAT_PATTERN_ERROR);
        }
        return FastExcel.read(fileName).head(clazz).sheet().doReadSync();
    }
    
    public <T> void writeToResponse(
            String fileName,
            String sheetName,
            Class<T> tClass,
            Collection<T> collection,
            HttpServletResponse response,
            boolean writeToLocal
    ) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        FastExcel.write(response.getOutputStream(), tClass).sheet(sheetName).doWrite(collection);
        String finalFileName = fileName;
        // 根据需要，保存到本地
        if (writeToLocal) {
            executorService.execute(() -> {
                writeToLocal(finalFileName, tClass, sheetName, collection);
            });
        }
    }
    
    public <T> Collection<T> readMultipartFile(
            MultipartFile file,
            Class<T> tClass
    ) throws IOException {
        String originalFilename = file.getOriginalFilename();
        if (!FileUtil.verifyFile(originalFilename, FileUtil.EXCEL_FORMAT_PATTERN)) {
            throw new RuntimeException(EXCEL_FORMAT_PATTERN_ERROR);
        }
        return FastExcel.read(file.getInputStream()).head(tClass).sheet().doReadSync();
    }
    
}
